//
//  ModelConvertible.swift
//  TTProduct
//
//  Created by Toj on 1/15/21.
//  模型转换

import Foundation

public extension Encodable {
    
    var cm_dictionary: [String: Any] {
        guard let data = cm_data else {return [:]}
        return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
    }
    
    subscript(key: String) -> Any? {
        return cm_dictionary[key]
    }
    
    var cm_data: Data? {
        return try? JSONEncoder().encode(self)
    }
    
    var cm_json: String? {
        guard let data = cm_data else {return nil}
        return String(data: data, encoding: .utf8)
    }
}

public extension Decodable {
    static func cm_model(data: Data) -> Self? {
        return try? JSONDecoder().decode(self, from: data)
    }
    
    static func cm_model(json string: String) -> Self? {
        guard let data = string.data(using: .utf8) else {return nil}
        return cm_model(data: data)
    }
    
    static func cm_model<Key: Hashable,Value>(dict: Dictionary<Key,Value>) -> Self? {
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .fragmentsAllowed) else {return nil}
        return cm_model(data: data)
    }
}
